import {
  createRouter,
  createWebHistory,
  type RouteRecordRaw,
} from "vue-router";
import { useUserStore } from "@/store/useUserStore";
import { storeToRefs } from "pinia";
import { reqGetRolePerm } from "@/api/reqRole";
import type { USER } from "@/types/user";

const routes: RouteRecordRaw[] = [
  {
    path: "/",
    component: () => import("@/layout/index.vue"),
    redirect: "/home",
    children: [
      {
        path: "/home",
        component: () => import("@/views/Home/index.vue"),
      },
      {
        path: "/user",
        component: () => import("@/views/User/index.vue"),
        meta: {
          isAuth: true,
        },
      },
      {
        path: "/role",
        component: () => import("@/views/Role/index.vue"),
        meta: {
          isAuth: true,
        },
      },
      {
        path: "/major",
        component: () => import("@/views/Major/index.vue"),
        meta: {
          isAuth: true,
        },
      },
      {
        path: "/class",
        component: () => import("@/views/Class/index.vue"),
        meta: {
          isAuth: true,
        },
      },
      {
        path: "/student",
        redirect: { name: "main" }, // 通常直接使用对象而不是数组
        component: () => import("@/views/Student/index.vue"),
        children: [
          {
            path: "main",
            name: "main",
            component: () => import("@/views/Student/main/index.vue"),
          },
          {
            path: "add",
            name: "add",
            component: () => import("@/views/Student/addAndEdit/index.vue"),
          },
          {
            path: "edit/:id",
            name: "edit",
            component: () => import("@/views/Student/addAndEdit/index.vue"),
          },
        ],
        meta: {
          isAuth: true, // 控制是否需要认证
          root: "/student",
        },
      },
      {
        path: "/school",
        component: () => import("@/views/School/index.vue"),
        meta: {
          isAuth: true,
          root: "student",
        },
      },
    ],
    beforeEnter(to, from, next) {
      const store = useUserStore();
      const { user } = storeToRefs(store);
      if (user.value.name) {
        next();
      } else {
        next("/login");
      }
    },
  },
  {
    path: "/login",
    component: () => import("@/views/login.vue"),
    beforeEnter(to, from, next) {
      // 判断userStore里面是否有user
      const store = useUserStore();
      const { user } = storeToRefs(store);
      if (user.value.name) {
        next("/");
      } else {
        next();
      }
    },
  },
  {
    // 404配置
    path: "/:matchAll(.*)",
    component: () => import("@/views/notFound.vue"),
  },
  {
    path: "/notPerssion",
    component: () => import("@/views/notPerssion.vue"),
  },
];
const router = createRouter({
  history: createWebHistory(),
  routes,
});

function checkSame<T>(oldArr: T[] = [], newArr: T[]): boolean {
  if (oldArr.length !== newArr.length) {
    return false;
  }
  for (let i = 0; i < oldArr.length; i++) {
    const m = oldArr[i];
    if (!newArr.includes(m)) {
      return false;
    }
  }
  return true;
}

// 全局路由守卫
router.beforeEach(async (to, from, next) => {
  const store = useUserStore();
  const oldMenus = store.menus;
  // 当前用户对应的角色的权限发生变化，我们需要重新登录
  // 每次跳转的时候，我需要获取你的身份获取最新的权限
  const { data } = await reqGetRolePerm(store.user.role?._id as string);
  const newMenus = data?.menus || [];

  if (checkSame(oldMenus as string[], newMenus) === false) {
    localStorage.removeItem("vue3-token");
    // @ts-ignore
    store.user = {};
    next("/login");
    return;
  }

  // 结构赋值 本质：对应相等
  // const [a, b] = [1, 2]
  // a = 1, b = 2
  // const {
  //   a: { b },
  // } = {
  //   a: {
  //     b: 1,
  //   },
  // }
  // 发送请求获取最新的权限
  // 跟你的权限作比较 store.user.role.menus

  if (to.meta.isAuth) {
    // 需要鉴权
    if (
      oldMenus?.includes(to.path) ||
      oldMenus?.includes(to.meta.root as string)
    ) {
      next();
    } else {
      next("/notPerssion");
    }
  } else {
    next();
  }
});

export default router;
